package com.cn.wanxi.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 1.注册数据库驱动?什么时候注册？需不需要每次都注册？,下载mysql驱动
 * 2.取得链接
 * ----------3.创建sql语句
 * 4.获取执行对象
 * 5.操作
 * 1.增删改操作
 * 2.查询操作
 * 6.处理结果
 * 7.关闭结果集
 */
public class JDBC {
    static {
        try {
            // 反射，得到对象的三种方式
//        Class<?> resultModel= Class.forName("com.cn.wanxi.model.ResultModel");
//            com.mysql.jdbc.Driver  MySQL 5.7
//            com.mysql.cj.jdbc.Driver mysql 8.0
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private JDBC() {
    }

    private static Connection getConnection() {
        String url = "jdbc:mysql://121.199.55.96:3306/canyin04";
        String user = "canyin04";
        String password = "123456";
        try {
            return DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回影响的条数
     *
     * @param sql
     * @return
     */
    public static int update(String sql, List list) {
        try {
//            获取执行对象
//            Statement和PreparedStatement之间的区别？
            PreparedStatement prepardStatement = getConnection().prepareStatement(sql);
//            prepardStatement.setString(1, "address");
//            prepardStatement.setString(2, "qq.com");
//            prepardStatement.setString(3, "aa");
//            prepardStatement.setString(4, "aa");
//            prepardStatement.setString(5, "aa");
//            prepardStatement.setString(6, "aa");
//            prepardStatement.setInt();
//            Object[] data={"","",11};
//            List list = new ArrayList();
            for (int i = 0; i < list.size(); i++) {
                prepardStatement.setObject(i + 1, list.get(i));
            }
//            执行
            return prepardStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static ResultSet query(String sql, List list) {
        try {
//            获取执行对象
            PreparedStatement prepardStatement = getConnection().prepareStatement(sql);
            for (int i = 0; i < list.size(); i++) {
                prepardStatement.setObject(i + 1, list.get(i));
            }
//            执行
            return prepardStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
//        System.out.println(getConnection());
    }
}
